#工具层  将常用的行为进行封装
import logging
import allure,json,requests
import jsonpath
from requests.exceptions import RequestException
from config.config import config


#定义一个关键字类
class ApiKey():

    @allure.step('HTTP请求')
    def http(self, case_method, test_url, data=None, params=None, **Kwargs):

        method = str(case_method).lower()
        if method in ['get', 'post', 'put', 'delete']:
            try:
                base_url = config.API_BASE_URL
                url = base_url + test_url
                # auth_token = {"Authorization": f"Bearer {config.AUTH_TOKEN}"}
                Cookie = config.COOKIE
                Headers = {
                    "Cookie": Cookie
                }
                logging.info(f'请求方式：{method}')
                logging.info(f"接口地址：{url}")
                logging.info(f"请求头值：{Headers}")
                if method == 'get':
                    logging.info(f"请求头值：{params}")
                    requests = self.get(url, params, Headers)
                elif method == 'post':
                    logging.info(f"请求体值：{data}")
                    requests = self.post(url, data, Headers)
                elif method == 'put':
                    logging.info(f"请求体值：{data}")
                    requests = self.put(url, data, Headers)
                else:
                    logging.info(f"请求体值：{data}")
                    requests = self.delete(url, data, Headers)

                return requests
            except RequestException as e:
                logging.error(f'请求失败：{e}')
                raise
        else:
            logging.error(f'请使用正确的请求方式：{method}')
            raise ValueError(f'不支持的请求方式：{method}')


    @allure.step('POST请求')
    def post(self, url, data,headers=None, **Kwargs):
        return requests.post(url=url, data=data, headers=headers, **Kwargs)


    @allure.step('GET请求')
    #**kwargs 的作用是将所有额外的关键字参数直接传递给 requests.get() 方法
    def get(self, url,params=None, headers=None, **Kwargs):
        return requests.get(url=url,params=params, headers=headers,**Kwargs)


    @allure.step('PUT请求')
    def put(self, url, data, headers=None, **Kwargs):
        return requests.post(url=url, data=data, headers=headers, **Kwargs)


    @allure.step('DELETE请求')
    def delete(self, url, data, headers=None, **Kwargs):
        return requests.post(url=url, data=data, headers=headers, **Kwargs)




    # #获取接口的返回值
    # @allure.step('获取返回值')
    # def get_value(self,data,key):
    #     json_data = json.loads(data)
    #     value = jsonpath.jsonpath(json_data,'$..{0}'.format(key))
    #     return value[0]
    @allure.step('获取返回值')
    def get_value(self, data, key):
        json_data = json.loads(data)
        # 修正字段名：将 'msg' 改为 'message'
        value = jsonpath.jsonpath(json_data, f'$..{key}')

        # 增加结果校验：若匹配失败（value 为 False 或空列表），返回默认值
        if not value:
            return "未获取到值"  # 或根据业务需求返回其他默认值

        return value[0]



